﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace furion.blog.Domain.Shared.ValidateAttribute
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
    public class IdNumValidateAttribute : ValidationAttribute
    {
        private Regex regex = new Regex(@"^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$");

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                this.ErrorMessage = "请填写身份证号码";
                return false;
            }

            if (regex.IsMatch(value.ToString()))
            {
                return true;
            }
            this.ErrorMessage = "身份证号码有误";
            return false;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return new ValidationResult("请填写身份证号码");
            }

            if (regex.IsMatch(value.ToString()))
            {
                return ValidationResult.Success;
            }
            return new ValidationResult("身份证号码有误");
        }
    }
}
